import { getInfos, delInfos, addInfos, updateInfos } from '@/api';
import { Button, Form, Input, Modal, Popconfirm, Select, Space, Switch, Table, message } from 'antd'
import type { TableProps } from 'antd';
import React, { useEffect, useState } from 'react'

function Index() {

  const [form] = Form.useForm()

  // 咨询表格数据
  const [infos, setInfos] = useState()
  //咨询名称搜索
  const [infoName, setInfoName] = useState("")
  // 状态选择
  const [stateVal, setStateVal] = useState("")
  // 模态窗
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 模态窗标题
  const [titleType, setTitleType] = useState("")

  const [id, setId] = useState("")

  useEffect(() => {
    (
      async (data: any) => {
        let res = await getInfos(data)
        // console.log(res)
        setInfos(res.data.data.map((item: any) => {
          item.key = item.id
          return item
        }))
      }
    )(infos)
  }, [])

  const columns: TableProps<any>['columns'] = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      render: (text) => <div style={{ width: 100 }}>{text}</div>,
    },
    {
      title: '文章标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '创建人',
      dataIndex: 'uid',
      key: 'uid',
      width: 100
    },
    {
      title: '创建日期',
      dataIndex: 'create_time',
      key: 'create_time',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (_, record) => {
        if (record.status == 0) {
          return <Switch checkedChildren="开启" unCheckedChildren="关闭" />
        } else if (record.status == 1) {
          return <Switch checkedChildren="开启" unCheckedChildren="关闭" defaultChecked />
        }
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (record) => (
        <Space size="middle">
          <a onClick={() => editModal(record)}>编辑</a>
          <Popconfirm
            // title="Delete the task"
            title={undefined}
            description="确认删除吗?"
            onConfirm={() => confirm(record)}
            onCancel={cancel}
            okText="是"
            cancelText="否"           >
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];



  // 状态事件
  const handleChange = (value: string) => {
    setStateVal(value)
    if (value === "请选择") {
      setStateVal("")
      getInfos([]).then((res: any) => {
        setInfos(res.data.data.map((item: any) => {
          item.key = item.id
          return item
        }))
      })
    }
  };

  // 删除资讯数据
  const confirm = async (data: any) => {
    let res = await delInfos(data.id)
    message.success(res.data.message)
    // 重新获取数据
    getInfos([]).then(((res: any) => {
      setInfos(res.data.data.map((item: any) => {
        item.key = item.id
        return item
      }))
    }))
  }
  const cancel = () => {
    message.error('取消删除');
  };

  // 搜索框事件
  const handelChange_1 = (e: any) => {
    if (e.target.value == "") {
      getInfos([]).then((res: any) => {
        setInfos(res.data.data.map((item: any) => {
          item.key = item.id
          return item
        }))
      })
    }
    setStateVal(e.target.value)
  }


  // 查询事件
  const btnCha = async () => {
    let res = await getInfos({ title: infoName, status: stateVal })
    if (res.data.code == 1) {
      message.success(res.data.msg)
      setInfos(res.data.data.map((item: any) => {
        item.key = item.id
        return item
      }))
    } else {
      message.error(res.data.msg)
      setInfos(res.data.data.map((item: any) => {
        item.key = item.id
        return item
      }))
    }
  }

  // 模态窗新增事件
  const addModal = () => {
    setIsModalOpen(true);
    setTitleType("新增")
  };

  // 编辑事件
  const editModal = async (obj: any) => {
    setId(obj.id)
    setIsModalOpen(true);
    setTitleType("编辑")
    form.setFieldsValue(obj)    // 回显内容
  }
  // 确定事件
  const handleOk = () => {

  };

  // 取消事件
  const handleCancel = () => {
    setIsModalOpen(false);
    form.resetFields();
  };

  // 表单提交事件
  const onFinish = async (values: any) => {
    if (titleType == "新增") {
      let res = await addInfos(values)
      if (res.data.code === 1) {
        message.success('新增成功')
        // 新增成功重新渲染 数据
        getInfos([]).then(((res: any) => {
          setInfos(res.data.data.map((item: any) => {
            item.key = item.id
            return item
          }))
        }))
      }
    } else {
      let res = await updateInfos({ id, ...values })
      message.success(res.data.message)
    }
    setIsModalOpen(false)   //关闭模态窗
    form.resetFields();     //重置表单，清空表单内容
  };

  return (
    <>
      <p>资讯管理</p>

      <div className="boxZi">
        搜索：<Input placeholder='咨询名称' style={{ width: 200 }} onChange={handelChange_1} />
        状态：<Select
          defaultValue="请选择"
          style={{ width: 200 }}
          onChange={handleChange}
          options={[
            { value: '请选择', label: '请选择' },
            { value: '1', label: '开启' },
            { value: '0', label: '关闭' },
          ]}
        />&emsp;
        <Space>
          <Button type='primary' disabled={infoName.length || stateVal.length ? false : true} onClick={btnCha}>查询</Button>
          <Button type='primary' onClick={addModal}>新增</Button>
        </Space>

        {/* 模态窗 */}
        <Modal title={titleType} open={isModalOpen} okText='确定' cancelText='取消' onOk={handleOk} onCancel={handleCancel} footer={null}>
          <Form
            name="basic"
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            onFinish={onFinish}
            form={form}
            autoComplete="off"
          >
            <Form.Item
              label="文章标题"
              name="title"
            >
              <Input.TextArea placeholder='文章标题：限制50个文字' maxLength={50} />
            </Form.Item>
            <Form.Item
              label="文章内容"
              name="articel"
            >
              <Input.TextArea style={{ minHeight: 100 }} placeholder='文章内容：限制200个文字' maxLength={200} />
            </Form.Item>
            <Form.Item
              label="创建人"
              name="uid"
            >
              <Input style={{ width: 150 }} placeholder='uid:布丁🍮' />
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 20, span: 18 }}>
              <Button type="primary" htmlType="submit" className='formBtn'>
                确定
              </Button>
            </Form.Item>
          </Form>
        </Modal>

        {/* 表格 */}
        <Table columns={columns} dataSource={infos} scroll={{ x: 800, y: 400 }} bordered />
      </div>
    </>
  )
}

export default Index